

//
//  ZLibViewController.m
//  ZQLearn
//
//  Created by admin on 2019/4/18.
//  Copyright © 2019 admin. All rights reserved.
//

#import "ZLibViewController.h"
#import "LibCollectionViewCell.h"
#import "LibraryModel.h"
#import "ZLibCategoryListViewController.h"
#import "WXApi.h"
@interface ZLibViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property(nonatomic,strong)UICollectionView *collectionView;
@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,copy)NSString *txtContent;

@end

#define kLineNumber 3
NSString *const cellID = @"libid";

@implementation ZLibViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
//    self.view.backgroundColor = kBackgroundColor;
    self.navigationItem.leftBarButtonItem = nil;
    [self.navigationItem setItemWithTitle:@"K15智秦数字图书馆" textColor:kNavigationTitleColor fontSize:18 itemType:center];
    
    [self addNavgationRightButtonWithFrame:CGRectMake(0, 0, 35, 35) title:@"" Image:@"" selectedIMG:@"" tartget:self action:@selector(testEBook)];
    
    self.dataArray = [NSMutableArray array];
    
    [self.view addSubview:self.collectionView];
    
    [self loadData];
    
    // Do any additional setup after loading the view.
}

- (void)testEBook{
    
//    [self saveTxt];
//    return;
////    NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"kelu"withExtension:@"txt"];
//    dispatch_async(dispatch_get_global_queue(0, 0), ^{
////        XDSBookModel *bookModel = [XDSBookModel getLocalModelWithURL:fileURL];
//        NSString *string = @"\n\n第一章 可鲁诞生\n\n 住在京都的仁井勇、仁井三都子夫妇开始公益性的领养活动是1984年的事情。只有夫妻两个人的生活，自从那像孩子一样受宠爱的牧羊犬死后，家中就变得用一句话说“有如灯灭一般”的静寂。两个人都非常喜欢狗，虽然总在说“再养一只吧”，但一想到爱犬死了引起的那种悲痛，就一直没能有勇气再养狗。当他们在报纸上看到关西导盲犬协会征集\n\n\n\n第二章 军营生活\n\n 没有办法细心照顾小狗。因为这个缘故吧，兰跟他们不太亲近。跟它说“走，去散步”，它根本不动弹，经常不太听话，还曾经咬伤过仁井勇先生。领养已经两个月了，对于它，“我们基本上是无可奈何的投降状态”，仁井夫妇在回忆当时的情况时，这样说道。好在兰最后还是成为了一只导盲犬，并开始工作了，两人才放下心来。领养的第二只狗——娇娜成为导盲犬之后，陪伴着它的主人宫本武先登上了富士山和白山，还巡游了四国、秩父、坂东的百观音等一些地方，让它的“养父母”仁井夫妇非常高\n\n第三章 野外行军\n\n   有一块仙石。其石有三丈六尺五寸高，有二丈四尺围圆。三丈六尺五寸高，按周天三百六十五度；二丈四尺围圆，按政历二十四气，上有九窍八孔，按九宫八卦。四面更无树木遮阴，左右倒有芝兰相衬。盖自开辟以来，每受天真地秀，日精月华，感之既久，遂有灵通之意，内育仙胎。一日迸裂，产一石卵，似圆球样大，因见风，化作一个石猴，五官俱备，四肢皆全。便就学爬学走，拜了四方，目运两道金光，射冲斗府，惊动高天上圣大慈仁者玉皇大天尊玄穹高上帝，驾座金阙云宫灵霄宝殿，聚集仙卿，见有金光焰焰，即命千里眼、顺风耳开南天门观看。二将果奉旨出门外，看的真，听的明，须臾回报道";
//        self.txtContent = [NSString stringWithFormat:@"\n\n\n\n\n版权信息\n\n书名：再见可鲁\n作者：jimsmith    \n\n\n%@\n\n\n\n",string];
//        XDSBookModel *bookModel = [[XDSBookModel alloc]initWithContent:self.txtContent];
//        dispatch_async(dispatch_get_main_queue(), ^{
//            XDSReadPageViewController *pageView = [[XDSReadPageViewController alloc] init];
////            [[XDSReadManager sharedManager] setResourceURL:fileURL];//文件位置
//            [[XDSReadManager sharedManager] setBookModel:bookModel];
//            [[XDSReadManager sharedManager] setRmDelegate:pageView];
//            [self presentViewController:pageView animated:YES completion:nil];
//        });
//    });
//
}


#pragma mark - 缓存相关
///存txt文件
-(void)saveTxt{
    [self getCachesPath];
    //    [self createDirectory];
    [self createFile];
    [self writeFile];
}

// 获取caches路径
- (NSString *)getCachesPath {
    // 获取Caches目录
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSLog(@"path:%@", path);
    return path;
}

// 创建文件夹
//- (void)createDirectory {
//
//    NSString *documentsPath =[self getCachesPath];
//    NSFileManager *fileManager = [NSFileManager defaultManager];
//    NSString *iOSDirectory = [documentsPath stringByAppendingPathComponent:@"iOS"];
//    BOOL isSuccess = [fileManager createDirectoryAtPath:iOSDirectory withIntermediateDirectories:YES attributes:nil error:nil];
//    if (isSuccess) {
//        NSLog(@"success");
//    } else {
//        NSLog(@"fail");
//    }
//}


// 创建文件
- (void)createFile {
    NSString *documentsPath =[self getCachesPath];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *iOSPath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
    BOOL isSuccess = [fileManager createFileAtPath:iOSPath contents:nil attributes:nil];
    if (isSuccess) {
        NSLog(@"success");
    } else {
        NSLog(@"fail");
    }
}


// 写入文件
- (void)writeFile {
    NSString *documentsPath =[self getCachesPath];
    NSString *iOSPath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
    //    NSString *content = self.txtContent;
    NSString *content = @"玛丽玛丽后，获取路径后读取txt文件";
    BOOL isSuccess = [content writeToFile:iOSPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    if (isSuccess) {
        NSLog(@"write success");
    } else {
        NSLog(@"write fail");
    }
}



- (void)loadData{
    
    NSDictionary *dic  = @{@"pageIndex":@(1),@"pageSize":@(10)};
    [ZNetworkService getRequestWithBaseUrl:kLibraryListUrl setParameters:dic success:^(id result) {
        YYLog(@"***当前数据：%@",result);
        if ([result[@"errorCode"] integerValue]==0) {
            NSArray *arr = result[@"result"];
            for (NSDictionary *dict in arr) {
                LibraryModel *model = [LibraryModel mj_objectWithKeyValues:dict];
                NSString *url = [NSString stringWithFormat:@"%@%@",kPicServerUrl,model.photo];
                model.picUrl = url;
                [self.dataArray addObject:model];
            }
            [self.collectionView reloadData];
        }
        YYLog(@"%@",result);
        
    } fail:^(NSError *error) {
        
        YYLog(@"%@",error);
        
    } delegater:nil];
    
}

//流式布局
- (UICollectionViewFlowLayout *)flowLayout {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    //整个 section 的四周边界的margin
    layout.sectionInset = UIEdgeInsetsMake(5, 0, 5, 0);
    layout.minimumLineSpacing = 0.f;
    layout.minimumInteritemSpacing = 0.f;
    //    layout.headerReferenceSize = CGSizeMake(kScreenWidth, SectionHeaderHeight);
    return layout;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-kTabHeight-ScreenHeightFlex) collectionViewLayout:[self flowLayout]];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsVerticalScrollIndicator = NO;
        [self registerCell];
        //        WeakStament(ws);
        //        _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //            [ws refreshData];
        //        }];
        _collectionView.backgroundColor = kWhiteColor;
    }
    return _collectionView;
}

- (void)registerCell {
    
    [_collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([LibCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:cellID];
    
    //最后一个有一个尾视图  到时候需要用到
//    [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headReuseID];
    
}



#pragma datasource
//-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
//    return 1;
//}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count;
}



-(__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    LibCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    LibraryModel *model = self.dataArray[indexPath.row];
    [cell.HeadImage sd_setImageWithURL:[NSURL URLWithString:model.picUrl] placeholderImage:nil];
    return cell;
}



#pragma mark - delegate
//cell尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row==self.dataArray.count-1) {
        ///因为最后一个的大小和其他都不一样所以要单独处理
        CGFloat width=ScreenWidth;
        return CGSizeMake(width, 125);
        
    }else{
        
        CGFloat width=ScreenWidth/kLineNumber;
        return CGSizeMake(width, width);
    }
    return CGSizeZero;
}

///section header 尺寸
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
//    return CGSizeMake(ScreenWidth, SectionHeaderHeight-20);
//}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    ///
    ZLibCategoryListViewController *category = [ZLibCategoryListViewController new];
    LibraryModel *model = self.dataArray[indexPath.row];
    category.cateId = model.ID;
    category.ttitle = model.name;
    ///ZLibCategoryListViewController 此控制器共用，所以标记一下
    category.isFlag = @"lib";
    [UserModel shareInstance].isLib = YES;

    [self.navigationController pushViewController:category animated:YES];
    
}




@end
